import React, { useState } from 'react';
import styled from 'styled-components';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { PageLayout } from '@/components/grid/PageLayout';
import { SwipeAction, List, Image, Stepper, Button, Empty } from 'antd-mobile';
import { DeleteOutline } from 'antd-mobile-icons';

interface CartItem {
  id: string;
  name: string;
  price: number;
  image: string;
  description: string;
  stock: number;
  quantity: number;
}

const Cart: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useSelector((state: any) => state.theme);
  const location = useLocation();
  const [cartItems, setCartItems] = useState<CartItem[]>(
    location.state?.cartItems || []
  );

  const handleQuantityChange = (item: CartItem, quantity: number) => {
    if (quantity === 0) {
      setCartItems(prev => prev.filter(i => i.id !== item.id));
      return;
    }
    setCartItems(prev =>
      prev.map(i =>
        i.id === item.id ? { ...i, quantity } : i
      )
    );
  };

  const handleDelete = (itemId: string) => {
    setCartItems(prev => prev.filter(item => item.id !== itemId));
  };

  const getTotalPrice = () => {
    return cartItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
  };

  const handleCheckout = () => {
    navigate('/payment', {
      state: {
        items: cartItems,
        totalAmount: getTotalPrice(),
      },
    });
  };

  if (cartItems.length === 0) {
    return (
      <PageLayout title={t('订单.购物车.标题')}>
        <EmptyContainer>
          <Empty
            description={t('订单.购物车.为空')}
            imageStyle={{ width: 128 }}
          />
          <Button
            color="primary"
            onClick={() => navigate('/snack-order')}
            style={{ marginTop: 16 }}
          >
            {t('订单.购物车.去购物')}
          </Button>
        </EmptyContainer>
      </PageLayout>
    );
  }

  return (
    <PageLayout title={t('订单.购物车.标题')}>
      <Container>
        <List>
          {cartItems.map((item) => (
            <SwipeAction
              key={item.id}
              rightActions={[
                {
                  key: 'delete',
                  text: t('通用.删除'),
                  color: 'danger',
                  onClick: () => handleDelete(item.id),
                },
              ]}
            >
              <List.Item>
                <ItemContent>
                  <ImageWrapper>
                    <Image src={item.image} width={80} height={80} fit="cover" />
                  </ImageWrapper>
                  <ItemInfo>
                    <ItemName>{item.name}</ItemName>
                    <ItemPrice $theme={theme}>¥{item.price.toFixed(2)}</ItemPrice>
                    <StyledStepper
                      min={0}
                      max={item.stock}
                      value={item.quantity}
                      onChange={(value) => handleQuantityChange(item, value)}
                    />
                  </ItemInfo>
                </ItemContent>
              </List.Item>
            </SwipeAction>
          ))}
        </List>

        <Footer $theme={theme}>
          <TotalPrice>
            <span>{t('订单.购物车.总计')}:</span>
            <Amount>¥{getTotalPrice().toFixed(2)}</Amount>
          </TotalPrice>
          <CheckoutButton onClick={handleCheckout}>
            {t('订单.购物车.结算')}
          </CheckoutButton>
        </Footer>
      </Container>
    </PageLayout>
  );
};

export default Cart;

const Container = styled.div`
  padding: 12px;
  padding-bottom: 80px;
`;

const EmptyContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
`;

const ItemContent = styled.div`
  display: flex;
  gap: 12px;
`;

const ImageWrapper = styled.div`
  border-radius: 8px;
  overflow: hidden;
`;

const ItemInfo = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
`;

const ItemName = styled.div`
  font-size: 16px;
  font-weight: 500;
`;

const ItemPrice = styled.div<{ $theme: string }>`
  font-size: 18px;
  font-weight: 600;
  color: var(--adm-color-primary);

  ${props => props.$theme === 'pink' && `
    color: #EC4899;
  `}

  ${props => props.$theme === 'green' && `
    color: #10B981;
  `}

  ${props => props.$theme === 'sky' && `
    color: #0EA5E9;
  `}
`;

const StyledStepper = styled(Stepper)`
  --border-radius: 20px;
  --button-width: 28px;
  --input-width: 40px;
  --height: 28px;
  --input-font-size: 14px;
  --border-color: var(--adm-color-border);
`;

const Footer = styled.div<{ $theme: string }>`
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 64px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

  ${props => props.$theme === 'pink' && `
    box-shadow: 0 -2px 10px rgba(236, 72, 153, 0.05);
  `}

  ${props => props.$theme === 'green' && `
    box-shadow: 0 -2px 10px rgba(16, 185, 129, 0.05);
  `}

  ${props => props.$theme === 'sky' && `
    box-shadow: 0 -2px 10px rgba(14, 165, 233, 0.05);
  `}
`;

const TotalPrice = styled.div`
  display: flex;
  align-items: baseline;
  gap: 8px;
  color: var(--adm-color-text);
`;

const Amount = styled.span`
  font-size: 20px;
  font-weight: 600;
  color: var(--adm-color-danger);
`;

const CheckoutButton = styled(Button)`
  --background-color: var(--adm-color-primary);
  --text-color: white;
  --border-radius: 20px;
  min-width: 120px;
  font-weight: 500;
`; 